package com.gitee.kamismile.stone.rpc.api.invocation.support;

import com.gitee.kamismile.stone.rpc.api.invocation.IStoneFilter;
import com.gitee.kamismile.stone.rpc.common.invocation.StoneInvocationType;
import com.gitee.kamismile.stone.rpc.common.support.StoneURL;
import com.gitee.kamismile.stone.rpc.common.utils.StoneBeanUtilsApplication;
import org.springframework.util.Assert;

import java.lang.reflect.Method;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StoneInvocationFactory {
    private StoneInvocationFactory() {
    }


    public static StoneInvocation createInvocation(Class<?> mapperInterface, Method method, StoneURL stoneURL, StoneInvocationType invocationType) {
        Map<String, IStoneFilter> stoneFilterMap = StoneBeanUtilsApplication.getApplicationContext().getBeansOfType(IStoneFilter.class);

        List<IStoneFilter> stoneFilters = stoneFilterMap.values().stream().filter(v -> v.getInvocationType().equals(invocationType)).sorted(Comparator.comparing(IStoneFilter::order)).collect(Collectors.toList());

        Assert.notEmpty(stoneFilters, invocationType.name() + " is empty");

        StoneInvocation stoneInvocation = new StoneInvocation();
        stoneInvocation.setStoneFilters(stoneFilters);
        method.setAccessible(true);

//        VertxAddress vd = AnnotationUtils.findAnnotation(method, VertxAddress.class);
//        Assert.notNull(vd, " must have VertxAddress");

        stoneInvocation.setType(mapperInterface);
        stoneInvocation.setStoneURL(stoneURL);
        return stoneInvocation;
    }
}
